<template>
  <div>
    <TopFilter ref="formPanel" :list="formList" :cols="3" :rows="2" :labelWidth="90" @filterChange="searchHealthHandle" @onCollapse="collapseHandle"></TopFilter>

    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :datakey="'rows'"
      :params="fetchParams"
      selectionType="single"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="SelectChange"
      :height="250"
    >
      <template slot="controls">
        <el-button size="small" type="primary" @click="add">新增</el-button>
        <el-button size="small" type="primary" @click="deleteBut">删除</el-button>
        <el-button size="small" type="primary" @click="upload">上报</el-button>
        <el-button size="small" type="primary" @click="cancel">取消上报</el-button>
      </template>
    </FilterTable>

    <BaseDialog :visible.sync="addVisible" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <addDetailed :rowData="rowData" :type="type" @close="closeHandler" />
    </BaseDialog>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { getChexSelect, getPinpSelect, queryCase, deleteSave, uploadCase, cancelUpload } from '@/api/repair/repairExample/repairCaseUpload/index';
import addDetailed from './addDetailed';
import { jsonToHump } from '@/utils/index'; // 驼峰引用
import _ from 'lodash'; // 拷贝引用
import { getEmployeeNo, getUser } from '@/assets/js/auth';

export default {
  name: 'repairCaseQuery',
  components: {
    addDetailed
  },
  mixins: [dictionary],
  data() {
    this.BaseTable = null;
    this.conf = { add: '新增', edit: '编辑', detailed: '明细' };
    return {
      formList: this.createFormList(),
      fetchApi: queryCase,
      fetchParams: { xhrAbort: true }, // 调用数据
      columns: this.createTablelist(),
      addVisible: false, // 新增页面
      rowData: null, // 定义传参
      items: [], // 定义选中行ID
      biandId: '', // 品牌
      dialogTitle: '', // 定义标题
      type: '', // 定义类型
      employeeCode: '', // 操作员代码
      userName: '' // 操作员名称
    };
  },

  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.employeeCode = getEmployeeNo();
    this.userName = getUser();
    this.getBrandSelect();
  },
  methods: {
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '案例标题',
          fieldName: 'caseTitle'
        },
        {
          type: 'SELECT',
          label: '单据状态',
          fieldName: 'formStatus',
          itemList: this.createDictList('6701')
        },
        {
          type: 'SELECT',
          label: '品牌',
          fieldName: 'brand',
          change: val => {
            this.changePinpSelect(val);
          },
          itemList: []
        },
        {
          type: 'SELECT',
          label: '车系',
          fieldName: 'series',
          filterable: true,
          itemList: []
        },
        {
          type: 'INPUT',
          label: 'VIN码',
          fieldName: 'vin'
        },
        {
          type: 'RANGE_DATE',
          dateType: 'exactdaterange',
          label: '操作日期',
          fieldName: 'operationStart|operationEnd'
        },
        {
          type: 'RANGE_DATE',
          dateType: 'exactdaterange',
          label: '提交日期',
          fieldName: 'submitStart|submitEnd'
        }
      ];
    },
    createTablelist() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 80,
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.eidtHandle(props.row)}>
                  编辑
                </el-button>
                <span> </span>
                <el-button size="mini" type="text" onClick={() => this.detailHandle(props.row)}>
                  明细
                </el-button>
              </div>
            );
          }
        },
        {
          title: '案例标题',
          dataIndex: 'EXAMPLE_TITLE',
          sorter: true
        },
        {
          title: '品牌',
          dataIndex: 'BRAND_NAME',
          sorter: true
        },
        {
          title: '车系',
          dataIndex: 'SERIES_NAME',
          sorter: true
        },
        {
          title: 'VIN码',
          dataIndex: 'VIN',
          width: 150,
          sorter: true
        },
        {
          title: '行驶里程',
          dataIndex: 'MILEAGE',
          sorter: true,
          showOverflowTooltip: true
          // render: props => {
          //   return <span>{ props.row.MILEAGE.toFixed(2)}</span>;
          // }
        },
        {
          title: '故障类型',
          dataIndex: 'TROUBLE_DESC',
          sorter: true,
          showOverflowTooltip: true
        },
        {
          title: '车辆状况',
          dataIndex: 'VEHICLE_STATE_NAME',
          sorter: true,
          showOverflowTooltip: true
        },
        {
          title: '车辆大类',
          dataIndex: 'VEHICLE_CLASS_NAME',
          sorter: true,
          showOverflowTooltip: true
        },
        {
          title: '故障现象',
          dataIndex: 'RO_TROUBLE_DESC',
          sorter: true,
          showOverflowTooltip: true
        },
        {
          title: '故障诊断分析',
          dataIndex: 'TROUBLE_CAUSE',
          sorter: true,
          showOverflowTooltip: true
        },
        {
          title: '单据状态',
          dataIndex: 'STATUS',
          sorter: true,
          showOverflowTooltip: true,
          render: props => {
            return <span>{this.createDictText(props.row.STATUS, '6701')}</span>;
          }
        },
        {
          title: '备注',
          dataIndex: 'REMARK',
          sorter: true,
          showOverflowTooltip: true
        }
      ];
    },

    // 查询品牌
    async getBrandSelect() {
      const res = await getPinpSelect();
      this.formList.find(item => item.fieldName === 'brand').itemList = res.data.map(x => ({ value: x.brandId, text: x.brandName }));
    },
    // 品牌下拉框改变时
    changePinpSelect(id) {
      this.clearFormItem(this.formList.find(item => item.fieldName === 'series'));
      if (!id) return;
      this.getChexSelect(id);
      this.biandId = id;
    },
    // 查询品牌的车系
    async getChexSelect(id) {
      const res = await getChexSelect(id);
      this.formList.find(item => item.fieldName === 'series').itemList = res.data.map(x => ({ value: x.seriesId, text: x.seriesName }));
    },

    // 清空下拉框表当控件的值和下拉列表
    clearFormItem(item) {
      item.initialValue = undefined;
      item.itemList = [];
    },

    searchHealthHandle(val) {
      console.log(val, 'val');
      const params = Object.assign({}, val, { xhrAbort: false });
      this.fetchParams = params;
    },
    // 新增
    add() {
      this.type = 'add';
      this.showHandler();
    },
    // 点击明细按钮
    detailHandle(row) {
      this.type = 'detailed';
      this.rowData = _.cloneDeep(row);
      jsonToHump(this.rowData);
      this.showHandler();
    },
    // 点击编辑按钮
    eidtHandle(row) {
      this.type = 'edit';
      this.rowData = _.cloneDeep(row);
      jsonToHump(this.rowData);
      this.showHandler();
    },
    showHandler() {
      console.log(this.rowData, '传输数据');
      this.dialogTitle = `${this.conf[this.type]}案例`;
      this.addVisible = true;
    },

    // 选中行
    SelectChange(row) {
      this.items = [];
      console.log('row', row);
      this.items.push(row[0]);
      console.log('this.items', this.items);
    },
    // 删除
    async deleteBut() {
      if (this.items.length === 0) {
        return this.$notify.warning({ title: '提示信息', message: '请选择一条要删除的数据' });
      }

      console.log(this.items, '选中数据');
      let res = await deleteSave(this.items[0].ID);

      if (res.resultCode == 200) {
        this.$notify.success({ title: '提示信息', message: '删除成功' });
        // 重新加载数据显示
        this.fetchParams = { ...this.fetchParams };
      }
    },
    // 取消上报,只能在提交时候
    async cancel() {
      if (this.items.length === 0) {
        return this.$notify.warning({ title: '提示信息', message: '请选择一条要取消上报的数据' });
      }
      const itemList1 = this.items[0];
      if (parseInt(itemList1.STATUS) != 93551002) {
        return this.$notify.warning({ title: '提示信息', message: '单据状态为提交的单据,才能取消上报' });
      }

      let res = await cancelUpload(itemList1);
      if (res.resultCode == 200) {
        this.$notify.success({ title: '提示信息', message: '取消上报成功' });
        // 刷新数据显示状态
        this.fetchParams = { ...this.fetchParams };
      } else {
        return this.$notify.error({ title: '提示信息', message: res.errMsg });
      }
    },
    // 上报,状态录入和返回时候才能上报
    async upload() {
      if (this.items.length === 0) {
        return this.$notify.warning({ title: '提示信息', message: '请选择一条要上报的数据' });
      }
      const itemList = this.items[0];
      if (parseInt(itemList.STATUS) == 93551002) {
        return this.$notify.warning({ title: '提示信息', message: '单据状态为提交的单据,无法再次上报' });
      }
      console.log(this.items, '数据的长度');

      // let obj={
      //      ID:itemList.ID, //ID,
      //      EXAMPLE_TITLE:itemList.itemList, //案例标题
      //      VIN:itemList.VIN,//VIN码
      //      MILEAGE:itemList.MILEAGE, //行驶里程
      //      VEHICLE_CLASS_CODE:itemList.VEHICLE_CLASS_CODE,//故障类型CODE
      //      VEHICLE_CLASS_NAME:itemList.itemList,//故障类型名称
      //      VEHICLE_STATE_CODE:itemList.VEHICLE_STATE_CODE,//车辆状况CODE
      //      VEHICLE_STATE_NAME:itemList.VEHICLE_STATE_NAME,//车辆状况名字
      //      RO_TROUBLE_DESC:itemList.RO_TROUBLE_DESC,//故障现象
      //      TROUBLE_CAUSE:itemList.TROUBLE_CAUSE,//故障诊断分析
      //      REMARK:itemList.REMARK,//备注
      //      //操作员代码
      //      //操作员名称
      // };
      let res = await uploadCase(itemList);
      if (res.resultCode == 200) {
        this.$notify.success({ title: '提示信息', message: '上报成功' });
        // 刷新数据显示状态
        this.fetchParams = { ...this.fetchParams };
      } else {
        return this.$notify.error({ title: '提示信息', message: res.errMsg });
      }
    },
    // 子页面保存成功后关闭子页面并刷新主页面
    closeHandler(val, type) {
      this.addVisible = false;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    }
  }
};
</script>

<style scoped lang="less"></style>
